package com.fang.apg;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;

public class Server extends Thread {
    private DatagramSocket serverDs;

    public Server() {
        super("服务器：");
    }


    @Override
    public void run() {
        try {
            ////////////////////////////接收数据///////////////////////////////////
            serverDs = new DatagramSocket(8899);
            byte[] b = new byte[1024];
            DatagramPacket dp2 = new DatagramPacket(b,b.length);
            while(true){
                serverDs.receive(dp2);
                int len = dp2.getLength();
                String strPsg = new String(b,0,len);
                System.out.println(strPsg);


                //////////////////////////发送数据/////////////////////////////////////////
                Scanner sc = new Scanner(System.in);
                String strClientMsg = this.getName();
                strClientMsg += sc.next();
                DatagramPacket dp = new DatagramPacket(strClientMsg.getBytes(),strClientMsg.getBytes().length,
                        dp2.getSocketAddress());
                System.out.println(strClientMsg);
                serverDs.send(dp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
